package com.saascloud.auth.core;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 401跳转到认证服务器认证
 * 在认证服务器如果已经登陆带着授权码重定向会本系统的login接口;
 * 本系统携带授权码向认证服务器请求获得令牌
 */
//@Component
@Slf4j
public class CustomizedAuthenticationEntryPoint implements AuthenticationEntryPoint {

    public CustomizedAuthenticationEntryPoint(){
        log.warn("1111111111CustomizedAuthenticationEntryPoint");
    }
    @Autowired
    OAuthConfig oauthConfig;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        log.error("令牌无效.authException401", authException);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",401);
        map.put("result","令牌无效");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html; charset=utf-8");
        //按照系统自定义结构返回授权失败
        response.getWriter().write(JSON.toJSONString(map));
    }
}
